package exilim.exf1.cspacker.worker;

import java.io.File;
import java.util.Map;
import java.util.Map.Entry;

import javax.swing.SwingWorker;

import exilim.exf1.cspacker.CSPackerLogic;

/**
 * 
 * @author Janos
 * @version 16.08.2010 | 01:12:16
 * 
 */
public class PackageSequencesWorker extends SwingWorker<Boolean, Void> {

	private final File imageDir;
	private final Map<Integer, Map<Integer, File>> sequencesMap;

	public PackageSequencesWorker(final File imageDir, final Map<Integer, Map<Integer, File>> sequencesMap) {
		this.imageDir = imageDir;
		this.sequencesMap = sequencesMap;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see javax.swing.SwingWorker#doInBackground()
	 */
	@Override
	protected Boolean doInBackground() throws Exception {

		final int imagesToCopy = countImagesToCopy(this.sequencesMap);
		int progress = 0;

		boolean bSuccess = true;

		for (final Entry<Integer, Map<Integer, File>> sequence : this.sequencesMap.entrySet()) {
			final String folderName = CSPackerLogic.createSequenceFolderName(sequence.getValue());

			final File seqFolder = new File(this.imageDir.getAbsolutePath() + File.separator + folderName);
			if (!seqFolder.exists()) {
				final boolean mkdir = seqFolder.mkdir();
				if (mkdir) {
					System.out.println("Directory for sequence created: " + seqFolder.getAbsolutePath());
				} else {
					System.out.println("Directory for sequence couldn't be created: " + seqFolder.getAbsolutePath());
				}
			}

			for (final Entry<Integer, File> file : sequence.getValue().entrySet()) {

				// Thread.sleep(10);

				++progress;
				final int progressPerc = (int) (((double) progress / (double) imagesToCopy) * 100);
				setProgress(progressPerc);

				final File destFile = new File(seqFolder + File.separator + file.getValue().getName());
				final boolean bMoved = file.getValue().renameTo(destFile);
				if (bMoved) {
					System.out.println("Moved file to sequence folder: " + file.getValue().getAbsolutePath());
				} else {
					System.out.println("Couldn't move file to sequence folder: " + file.getValue().getAbsolutePath());
					bSuccess = false;
				}
			}
		}

		return bSuccess;
	}

	private int countImagesToCopy(final Map<Integer, Map<Integer, File>> sequencesMap) {
		int i = 0;
		for (final Entry<Integer, Map<Integer, File>> sequence : sequencesMap.entrySet()) {
			i += sequence.getValue().size();
		}
		return i;
	}

}
